package com.ajmd.onlineexam.scheduledTask;

import com.ajmd.onlineexam.entity.ImagePO;
import com.ajmd.onlineexam.mapper.ImageMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.scheduling.annotation.Scheduled;
import javax.annotation.Resource;
import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author ajmd
 * @since 2023/4/23 14:19
 *
 * 定时任务
 *
 */

@Component
public class ClearImg {
    @Resource
    private ImageMapper imageMapper;
    // 图片保存的根路径（从 application.yml 中读取）
    @Value("${spring.servlet.multipart.location}")
    private String location;

    @Scheduled(cron = "0 0 4 * * ?")//每天凌晨4点执行
    public void clearImage(){
        System.out.println("=======清理图片=======");
//        List<String> pathList=new ArrayList<>();
        //查询试题相关图片
        List<ImagePO> imagePOList = imageMapper.selectList(null);
        List<String> questionPathList = imagePOList.stream()
                .map(item->location+item.getPath()).collect(Collectors.toList());
        Set<String> fileNames = new HashSet<>();
        for (String path : questionPathList) {
            File file = new File(path);
            if (file.isFile()) {
                fileNames.add(file.getName());
            }
        }

        //清理试题图片
        File questionImgFolder = new File(location+"/img/questionImg");
        if (questionImgFolder.isDirectory()) {
            Stream.of(questionImgFolder.listFiles())// 判断是否为目录
                    .filter(file -> file.isFile() && !fileNames.contains(file.getName()))// 过滤出需要删除的文件
                    .forEach(File::delete);// 删除文件
        }
        //清理选项图片
        File optionImgFolder = new File(location+"/img/optionImg");
        if (optionImgFolder.isDirectory()) {
            Stream.of(optionImgFolder.listFiles())// 判断是否为目录
                    .filter(file -> file.isFile() && !fileNames.contains(file.getName()))// 过滤出需要删除的文件
                    .forEach(File::delete);// 删除文件
        }
//        //清理证件照
//        File optionImgFolder = new File(location+"/img/optionImg");
//        if (optionImgFolder.isDirectory()) {
//            Stream.of(optionImgFolder.listFiles())// 判断是否为目录
//                    .filter(file -> file.isFile() && !fileNames.contains(file.getName()))// 过滤出需要删除的文件
//                    .forEach(File::delete);// 删除文件
//        }
    }

    @Async
    public void handleClearImage(){
        clearImage();
    }
}
